/**************************************************************************
 *  Copyright (C) 2012 Atlas of Living Australia
 *  All Rights Reserved.
 *
 *  The contents of this file are subject to the Mozilla Public
 *  License Version 1.1 (the "License"); you may not use this file
 *  except in compliance with the License. You may obtain a copy of
 *  the License at http://www.mozilla.org/MPL/
 *
 *  Software distributed under the License is distributed on an "AS
 *  IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 *  implied. See the License for the specific language governing
 *  rights and limitations under the License.
 ***************************************************************************/

import org.codehaus.groovy.grails.commons.ApplicationHolder
import grails.converters.JSON
import au.com.bytecode.opencsv.CSVWriter

/**
 * Script to convert charcters in JSON format to CSV as used by ALA Species List webapp.
 * Usage: grails run-script src/groovy/CharsJsonToCsv.groovy
 * 
 * @author Nick dos Remedios (nick.dosremedios@csiro.au)
 */
def main = {
    // read in json character and output CSV
    def charsJsonStr = ApplicationHolder.application.parentContext.getResource("classpath:resources/Acacia characters trin.json").inputStream.text
    def chars = JSON.parse(charsJsonStr) //  returns JsonElement: either JsonArray or JsonObject
    def headerAdded = false
    def internalSeparator = "||"
    def file = new File("/tmp/Acacia characters trin.csv")

    file.withWriter { writer ->
        def csvWriter = new CSVWriter(writer)

        chars.each { ch ->
            def name = ch.key
            def props = ch.value

            if (!headerAdded) {
                // write CSV heders
                def headers = ["scientificName"] // taxon goes on front of CSV line
                props.each { c ->
                    headers.add(c.key.replaceAll(/_+/," "))
                }
                println "headers = " + headers.join("|")
                csvWriter.writeNext(headers as String[])
                headerAdded = true
            } else {
                // write characters
                def values = [name]
                props.each { p ->
                    //def prop = p.value.join(internalSeparator).replaceAll("\"","%%") // join array values and remove JSON string quotes
                    def newProps = []
                    //println "props = " + p
                    //println " - p.value type = " + p.value.class
                    p.value.each {
                        newProps.add(it)
                        //println " -- it type = " + it.class + " value = " + it
                    }
                    values.add(newProps.join(internalSeparator))
                }
                //println "values = " + values.join("|")
                csvWriter.writeNext(values as String[])
            }
        }

        csvWriter.flush()
    }
}

main()
//def runit = new CharsJsonToCsv()
